package eva.savant.business.ventas.view

import org.primefaces.model.DefaultStreamedContent
import org.primefaces.model.StreamedContent

import javax.faces.bean.ManagedBean
import javax.faces.bean.SessionScoped
import javax.annotation.PostConstruct

@SessionScoped
@ManagedBean(name = 'IILibroVentas')
public class IILibroVentas extends Bean {

  Date dateIni, dateEnd

  def report, lsReport=['Libro Ventas':'libroVentas',
                        'Libro Ventas Renta':'libroVentasRenta',
                        'Libro Ventas Renta Txt':'libroVentasRentaTxt']

  StreamedContent result

  @PostConstruct
  public void cleanEntity() {

    lsEntity = null

    dateIni= dateEnd= new Date()
  }

  public List findLsEntity() {

    def name= 'VENTAS_' + dateIni.format('MMyyyy') + '_' + sociedad.nit; form= true

    def tipo= report.endsWith('Txt')? 'txt':'xls', p= ['iniDate':toStartDay(dateIni), 'finDate':toMidnight(dateEnd)]

    def x= tipo.equals('xls')? reportService.reportToXLS(report+'',p) : reportService.reportToTXT(report+'',p).bytes

    result= new DefaultStreamedContent(new ByteArrayInputStream(x),"application/$tipo","$name.$tipo")

    return null
  }

  public StreamedContent getReportXLS() throws IOException {

    return result
  }

}